package projet.volleystat;

import projet.volleystat.bdd.VolleyRepository;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditPlayerActivity extends Activity {
	protected VolleyRepository volleyDataBase;
	protected int idplayer;
	protected Player player;
	protected EditText inputname;
	protected EditText inputfirstname;
	protected EditText inputnationality;
	protected Button validateb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_player);

		inputname = (EditText) findViewById(R.id.inputplayername);
		inputfirstname = (EditText) findViewById(R.id.inputplayerfirstname);
		inputnationality = (EditText) findViewById(R.id.inputnationalityplayer);
		validateb = (Button) findViewById(R.id.validateEditButton);

		Bundle bundle = getIntent().getExtras();
		idplayer = bundle.getInt("id");
		volleyDataBase = new VolleyRepository(getApplicationContext());
		volleyDataBase.open();

		if (idplayer == -1) {
			player = new Player();
		} else {
			try {
				player = volleyDataBase.getPlayerById(idplayer);
			} catch (DatabaseException e) {
				e.printStackTrace();
			}

			inputname.setText(player.getName());
			inputfirstname.setText(player.getFirstname());
			inputnationality.setText(player.getNationality());

		}

		validateb.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				player.setName(inputname.getText().toString());
				player.setFirstname(inputfirstname.getText().toString());
				player.setNationality(inputnationality.getText().toString());
				try {
					volleyDataBase.commit(player);
				} catch (DatabaseException e) {
					e.printStackTrace();
				}
				finish();
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		volleyDataBase.open();
	}

	@Override
	public void onPause() {
		super.onPause();
		overridePendingTransition(0, 0);
		volleyDataBase.close();
	}
}
